package launcher.simple.android.woblog.cn.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;

import cn.woblog.android.common.utils.DimensionUtils;
import cn.woblog.android.common.utils.MyLog;
import launcher.simple.android.woblog.cn.simplelauncher.R;

/**
 * Created by ren on 2015/9/18 0018.
 */
public class AppView extends ViewGroup {

    private float scale = 1;

    private ScaleGestureDetector mScaleGestureDetector;


    /**
     * 默认x轴图标间距，缩放时将不是小于该值
     */
    private int default_HorizontalSpacing = 10;

    /**
     * 默认y轴图标间距，缩放时将不是小于该值
     */
    private int default_VerticalSpacing = 10;
    private int currentWidth = 40;
    private int currentHeight = 40;
    private boolean isScale = true;

    public AppView(Context context) {
        super(context);
        init(context, null);
    }

    public AppView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public AppView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public AppView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mScaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureListener());
//        TypedArray a = context.obtainStyledAttributes(attrs,
//                R.styleable.AppViewLayout);

//        try {
//            mHorizontalSpacing = a.getDimensionPixelSize(
//                    R.styleable.AppViewLayout_horizontal_spacing,
//                    getResources().getDimensionPixelSize(
//                            R.dimen.app_horizontal_spacing));
//
//            currentHorizontalSpacing = mHorizontalSpacing;
//
//            mVerticalSpacing = a.getDimensionPixelSize(
//                    R.styleable.AppViewLayout_vertical_spacing,
//                    getResources().getDimensionPixelSize(
//                            R.dimen.app_vertical_spacing));
//            currentVerticalSpacing = mVerticalSpacing;
//        } finally {
//            a.recycle();
//        }
    }

    public int getChildWidth(int i) {
        int i1 = (int) (getCurrentWidth(i) * scale);
        MyLog.d("getChildWidth:" + i1);
        return i1;
    }

    public int getChildHeight(int i) {
        int i1 = (int) (getCurrentHeight(i) * scale);
        MyLog.d("getChildHeight:" + i1);
        return i1;
    }

    public int getChildHalfWidth(int i) {
        return getChildWidth(i) / 2;
    }

    public int getChildHalfHeight(int i) {
        return getChildHeight(i) / 2;
    }

    public int getChildX(int i) {
        return ((LayoutParams) getChildAt(i).getLayoutParams()).x;
    }

    public int getChildY(int i) {
        return ((LayoutParams) getChildAt(i).getLayoutParams()).y;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        int width = getPaddingLeft();
//        int height = getPaddingTop();
            final int count = getChildCount();

            for (int i = 0; i < count; i++) {
                View child = getChildAt(i);
                // 测量每个子视图
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
                LayoutParams lp = (LayoutParams) child.getLayoutParams();
                switch (i) {
                    case 0:
                        int childHalfWidth = getChildHalfWidth(i);
                        int childHalfHeight = getChildHalfHeight(i);
                        MyLog.d("onMeasure:" + (childHalfWidth * 2) + "," + (childHalfHeight * 2));
                        lp.x = DimensionUtils.getCenterX() - getChildHalfWidth(i);
                        lp.y = DimensionUtils.getCenterY() - getChildHalfHeight(i);
                        break;

                    case 1: //左上角
                        lp.x = getChildX(0) - getChildWidth(i);
                        lp.y = getChildY(0) - getChildHeight(i);
                        break;
                    case 2: //右上角
                        lp.x = getChildX(0) + getChildWidth(i);
                        lp.y = getChildY(0) - getChildWidth(i);
                        break;

                    case 3://左下角
                        lp.x = getChildX(0) - getChildWidth(i);
                        lp.y = getChildY(0) + getChildWidth(i);
                        break;

                    case 4://右下角
                        lp.x = getChildX(0) + getChildWidth(i);
                        lp.y = getChildY(0) + getChildWidth(i);
                        break;

                    case 5://右下角
                        lp.x = getChildX(3) - getChildWidth(i);
                        lp.y = getChildY(3) - getChildWidth(i);
                        break;

                    case 6://右下角
                        lp.x = getChildX(4) + getChildWidth(i);
                        lp.y = getChildY(4) - getChildWidth(i);
                        break;

                    case 7://右下角
                        lp.x = getChildX(1) + getChildWidth(i);
                        lp.y = getChildY(1) - getChildWidth(i);
                        break;
                }



//        width += getPaddingRight();
//        height += getChildAt(getChildCount() - 1).getMeasuredHeight()
//                + getPaddingBottom();
//        // 使用计算所得的宽,高,设置整个布局的测量尺寸
//        setMeasuredDimension(resolveSize(width, widthMeasureSpec),
//                resolveSize(height, heightMeasureSpec));
        }
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

    private void setCurrentWidth(int measuredWidth) {
        if (currentWidth == 0) {
            currentWidth = measuredWidth;
        }
    }

    private void setCurrentHeight(int measuredHeight) {
        if (currentHeight == 0) {
            currentHeight = measuredHeight;
        }
    }

    private int getCurrentHeight(int i) {
        return currentHeight;
    }

    private int getCurrentWidth(int i) {
        return currentWidth;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            LayoutParams lp = (LayoutParams) child.getLayoutParams();
            int childWidth = getChildWidth(i);
            int childHeight = getChildHeight(i);

            MyLog.d("onLayout:" + childWidth + "," + childHeight);
            child.layout(lp.x, lp.y, lp.x + childWidth, lp.y
                    + childHeight);
        }
    }

    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams;
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p.width, p.height);
    }

    // 在编写onMeasure方法之前,先定义LayoutParams类,该类用于保存每个子视图的x,y
    public static class LayoutParams extends ViewGroup.LayoutParams {
        int x;
        int y;
        public int verticalSpacing;

        public LayoutParams(Context context, AttributeSet attrs) {
            super(context, attrs);

            TypedArray a = context.obtainStyledAttributes(attrs,
                    R.styleable.AppView_LayoutParams);
            try {
                verticalSpacing = a
                        .getDimensionPixelSize(
                                R.styleable.AppView_LayoutParams_layout_vertical_spacing,
                                -1);
            } finally {
                a.recycle();
            }
        }

        public LayoutParams(int w, int h) {
            super(w, h);
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        return mScaleGestureDetector.onTouchEvent(event);
    }

    public class ScaleGestureListener implements ScaleGestureDetector.OnScaleGestureListener {


        @Override
        public boolean onScale(ScaleGestureDetector detector) {

            //缩放比例
            scale = detector.getScaleFactor();
            requestLayout();
            MyLog.d("scale:" + scale + "," + getChildWidth(0) + "," + getChildHeight(0));
            isScale = true;
            return false;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
            //一定要返回true才会进入onScale()这个函数
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            // TODO Auto-generated method stub
//            currentVerticalSpacing = mVerticalSpacing;
//            currentHorizontalSpacing = mHorizontalSpacing;

            isScale = false;
            currentWidth = getChildWidth(0);
            currentHeight = getChildHeight(0);

        }

    }

}
